<?php
namespace app\index\controller;
use think\Controller;
use think\Cache;
use app\index\controller\BaseController;

class IndexController extends BaseController {
	protected function _initialize() {
		parent::_initialize();
		//$this -> auth_login();
	}
	public function guanzhu(){
		return $this->fetch();
	}
	
	public function about(){
	   	$about_config = get_config('about');
		$this->assign('about',$about_config);
		return $this->fetch();
	}
	public function do_share(){
		$res=db('member')->where("id",session("user_info")['id'])->setInc("share_nums",1);
		return json(["code"=>200]);
	}
	//确认消费
	public function qr_xiaofei(){
		$data['user_id']=session('user_info')['id'];
		$data['ticket_id']=input("ticket_id");
		$data['add_time']=now_time();
		$data['item_id']=input("item_id");
		$data['message']='消费';
		$w['user_id']=session("user_info")['id'];
		$w['ticket_id']=input('ticket_id');
		$w['item_id']=input("item_id");
		$xf=db("xiaofei")->where($w)->find();
		if($xf){
			$res=db("xiaofei")->where('id',$xf['id'])->setInc("nums",1);
		}else{
			$res=db("xiaofei")->insert($data);			
		}
		db("ticketlogs")->where("id",input("ticket_id"))->update(['use_status'=>2]);
		if($res){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>400,'msg'=>'操作失败']);
		}
		
	}
	//购票中心
	public function querendd() {
	   	$ticket_config = get_config('ticket_config');
		$this->assign('ticket_config',$ticket_config);
		return $this->fetch();
	}
	public function index() {
		$about_config =get_config('info');
		$this->assign('about',$about_config);
		$ads_info = db('advertise')->where('type',3)->select();
		$this->assign('ads', $ads_info);
		$url=config('API_DOMAIN')."index/index";
		$this->assign('url',$url);
		
		$share_config = get_config('share_config');
		$this->assign('share_title',$share_config['share_dbgl']);
		$this->assign('share_content',$share_config['share_dbgl_content']);
		
		return $this->fetch();
	}
	public function xf_list() {
		$list=db("xiaofei")->alias('a')->
		join("ticket_items b","a.item_id=b.id")->
		field("a.*,b.title")->where("user_id",session("user_info")['id'])->select();
		$this->assign('list',$list);
		return $this->fetch();
	}
	public function my_tickets(){
		$user_id=session('user_info')['id'];
		$where['status']=2;
		$where['user_id']=$user_id;
		$tickets=db('ticketlogs')->field('id,type,add_time,nums')->where($where)->order("add_time desc")->select();
		$this->assign('list',$tickets);
		return $this->fetch();
	}
	public function buyticket(){
		//$ticket_config = db('system')->field('value')->where('name', 'ticket_config')->find();
	   	$ticket_config = get_config('ticket_config');
		$this->assign('ticket_config',$ticket_config);
		
		$list = db("ticket_items")->order('sort desc')->select();
		$this->assign('list',$list);
		return $this->fetch();
	}
	//购票支付
	public function topay(){
	   	$ticket_config = get_config('ticket_config');
		$this->assign('ticket_config',$ticket_config);
		return $this->fetch();
	}
	//分享免费票
	public function shareticket(){
		$user_id=session('user_info')['id'];
		$my_shares=db("member")->where("id",$user_id)->field("share_nums")->find();
		$where['user_id']=$user_id;
		$where['type']=2;
		$log=db("ticketlogs")->where($where)->count("id");
		$this->assign('log',$log);
		$this->assign('shares',$my_shares['share_nums']);
		$url=config('API_DOMAIN')."index/index/shareticket.html";
		$this->assign('url',$url);
		
	   	$ticket_config = get_config('ticket_config');
		$share_num = $ticket_config['share_num'];
		$this->assign('share_num',$share_num);
		
		$share_config = get_config('share_config');
		$this->assign('share_title',$share_config['share_piao']);
		$this->assign('share_content',$share_config['share_piao_content']);
		return $this->fetch();
	}
	//免费票领取
	public function add_mticket(){
		$user_id=session('user_info')['id'];
	   	$ticket_config = get_config('ticket_config');
		$where['user_id']=$user_id;
		$where['type']=2;
		//每日领取张数和分享次数多少领取
		$limit=$ticket_config['ticket_daysum'];
		$nums=$ticket_config['share_num'];
		
		$log=db("ticketlogs")->where($where)->count("id");
		if($log){
			return json(["code"=>400,'msg'=>'每人限领一张,您已经领取过了!']);
		}
		$mem=db("member")->where("id",$user_id)->field("share_nums")->find();
		$my_shares=$mem['share_nums'];
		if($my_shares<$nums){
			return json(["code"=>400,'msg'=>'领取失败!您的分享次数未达到要求!']);
		}
		$today_lq=db("ticketlogs")->where('type',2)->wheretime("add_time","today")->count("id");
		if($today_lq>=$limit){
			return json(["code"=>400,'msg'=>'今日免费票已经发放完毕请明日再领!']);
		}
		$data['user_id']=$user_id;
		$data['add_time']=now_time();
		$data['balance']=0;
		$data['pay_balance']=0;
		$data['type']=2;
		$data['status']=2;
		$data['sn']=order_create_no();
		$result = db("ticketlogs")->insert($data);
		if($result){
			return json(["code"=>200,'msg'=>'领取成功']);
		}else{
			return json(["code"=>400,'msg'=>'领取失败']);
		}
	}
	public function ajax_asklist($page = 2){
		$ask = db('ask a')->field('a.*,m.nick_name,m.thumb')->join('member m', 'a.uid=m.id')->order('add_time desc')->page($page,4)->select();
		if ($ask) {
			$this->success('获取成功', '', $ask);
		} else {
			$this->error('没有数据了');
		}
	}

	public function login() {
		if (cookie('USER')) {
			$this->redirect('member/index');
		}
		if (request()->isPost()) {
			
			$phone = input('phone');
			$pwd = strFilter(input('pwd'));
			if (!is_numeric($phone)) {
				$this->error('参数错误');
			}
			$data['mobile'] = $phone;
			$data['password'] = md5_salt($pwd);
			$validate_result = $this->validate($data, 'Login');
			if ($validate_result !== true) {
				$this->error($validate_result);
			}
			$user = db('member')->field('thumb',true)->where($data)->find();
			if ($user) {
				if ($user['status'] == 1) {
					
					cookie('USER', $user,['prefix'=>'','expire'=>365*24*60*60]);
					//session('USER', $user);
					$url = cookie('URL') ? cookie('URL') : 'member/index';
					cookie('URL', null);
					$this->success('登录成功', 'member/index');
				} else {
					$this->error('用户账户禁用');
				}
			} else {
				$this->error('用户名或密码错误');
			}
		} else {
			return $this->fetch();
		}
	}

	/**
	 * 注册:第一步
	 */
	public function regist() {
		if ($this->request->isPost()) {
			$data['mobile'] = input('mobile');
			$data['password'] = input('password');
			$data['pid'] = input('pid', 0);
			if (!is_numeric(input('code')) || !is_numeric(input('pid')) || !is_numeric(input('mobile'))) {
				$this->error('非法访问');
			}
			$validate_result = $this->validate($data, 'Regist');
			if ($validate_result !== true) {
				$this->error($validate_result);
			}
			//验证码
			$result = $this->check_code($data['mobile'], input('code'), '用户注册');
			if ($result != 1) {
				$this->error('验证码错误!');
			}
			if ($data['pid']) {
				$p_member = db('member')->find($data['pid']);
				if ($p_member) {
					$data['pid'] = $p_member['id'];
				} else {
					$this->error('邀请人不存在');
				}
			}
			$data['password'] = md5_salt($data['password']);
			$data['add_time'] = now_time();
			$data['update_time'] = now_time();
			$data['login_time'] = now_time();
			$data['login_ip'] = $this->request->ip(0, 1);
			$result = db('member')->insertGetId($data);
			if ($result) {
				$member = db('member')->where('id', $result)->find();
				cookie('USER', $member,999999);
				$this->success('注册成功', url('member/index'));
			} else {
				$this->error('注册失败');
			}
		} else {
			return $this->fetch();
		}
	}

	/**
	 * 忘记密码
	 */
	public function forget() {
		if ($this->request->isPost()) {
			$password = input('password');
			$mobile = input('mobile');
			$code = input('code');
			if (!is_numeric($mobile) || !is_numeric($code)) {
				$this->error('非法访问');
			}
			$result = $this->check_code($mobile, $code, '找回密码');
			if ($result != 1) {
				$this->error('验证码错误或过期');
			}
			//手机号是否存在
			$p_member = db('member')->where('mobile', $mobile)->find();
			if (!$p_member) {
				$this->error('用户或手机号码不存在');
			}
			$data2['password'] = md5_salt($password);
			$result = db('member')->where("id", $p_member['id'])->update($data2);
			if ($result !== false) {
				$this->success('修改成功，请登录', url('index/login'));
			} else {
				$this->error('修改失败');
			}
		} else {
			return $this->fetch();
		}
	}

	public function logout() {
		cookie('USER', null);
		$this->success('退出成功', url('index/index'));
	}

	public function regist_code($mobile) {
		return $this->get_code(config('aliyun'), config('aliyun.regist_id'), $mobile, "用户注册");
	}

	public function forget_code($mobile) {
		return $this->get_code(config('aliyun'), config('aliyun.forget_id'), $mobile, "找回密码");
	}

	public function regist1() {
		return $this->fetch();
	}
	
	
	public function loan() {
		cookie('URL', url());
		if (!cookie('USER')) {
			$this->redirect('index/login');
		}
		$uid = cookie('USER')['id'];
		$model = db('loan')->where('uid', $uid)->find();
		if ($this->request->isPost()) {
			$data = $this->request->post();
			if (input('thumbs/a')) {
				$data['thumbs'] = implode(',', input('thumbs/a'));
			} else {
				$data['thumbs'] = '';
			}
			if ($model) {
				$data['update_time'] = now_time();
				$result = db('loan')->where('uid', $uid)->update($data);
			} else {
				$data['add_time'] = now_time();
				$data['uid'] = $uid;
				$result = db('loan')->insert($data);
			}
			if ($result !== false) {
				$this->success('保存成功', url('index/loan'));
			} else {
				$this->error('保存失败');
			}
		} else {
			if ($model['thumbs']) {
				$model['thumbs'] = explode(',', $model['thumbs']);
			}
			$this->assign('model', $model);
			return $this->fetch();
		}
	}
	
	//会员中心
	public function member() {
		$user_info = db('member')->where('open_id', session('openid'))->find();
		session('user_info', $user_info);
		$this->assign('user_info', $user_info);
		return $this->fetch();
	}
	
	/**
     * 获取验证码
     * 注意防盗刷
     * 
     */
    function verify_code(){   	
    	if(request()->isPost()){
    		return get_code($_POST['mobile'],1);
    	}
    }
	
	//绑定手机号
	function bdmobile(){
		if(request()->isPost()){
    		$res = check_sendcode($_POST['mobile'], $_POST['yzm'], '发送成功');
			if($res != 1) {
				$this->error('验证码错误或过期');
			}
			
			$data['mobile'] = $_POST['mobile'];
			$result = db('member')->where('id', session('user_info')['id'])->update($data);
			if ($result !== false) {
				$this->success('绑定成功', url('index/member'));
			} else {
				$this->error('绑定失败');
			}
		}
	}
	
	//我的矿石
	public function ks_list() {
		$user_id = session('user_info')['id'];
		$res = db('user_items')->alias("a")->join("action_item b","a.item_id=b.id")
		->where('a.user_id',$user_id)->where("b.type",1)->field("a.*,b.name,b.thumb")->select();
		$this->assign('item_info', $res);
		return $this->fetch();
	}		

	//商家联盟
	public function sj_list() {
		$user_id = session('user_info')['id'];	
		$goodstype = 0;
		$w=[];
		
		if(input('typeid')){
			$goodstype = input('typeid');
			$w['goodstype']=$goodstype;
		}
		
		$w['status'] = 1;
		
		$page=1;
		if($_POST){
			if(input("page")){
				$page=input("page");
			}
			$begin=($page-1)*20;
			$agent_info = db('agent')->where($w)->order("sort desc")->limit($begin,20)->select();
			return json(['list'=>$agent_info]);
		}
		$this->assign('goodstype', $goodstype);
		
		$ads_info = db('advertise')->where('type',1)->select();
		$this->assign('ads', $ads_info);
		
		$url=config('API_DOMAIN')."index/index/sj_list.html";
		$this->assign('url',$url);
		$types=db("goodstype")->where("pid",0)->select();
		$this->assign("types",$types);
		$share_config = get_config('share_config');
		$this->assign('share_title',$share_config['share_agent']);
		$this->assign('share_content',$share_config['share_agent_content']);
		return $this->fetch();
	}	
	public function mjp_list(){
		$user_id = session('user_info')['id'];
		$res = db('user_items')->alias("a")->join("action_item b","a.item_id=b.id")
		->where('a.user_id',$user_id)->where("a.nums>0")->where("b.type",2)->field("a.*,b.name,b.thumb,b.num")->select();
		$this->assign('list', $res);
		return $this->fetch();
	}
	//奖品列表
	public function jp_list() {
		$list = db("action_item")->where("type",2)->order("sort asc")->select();
		$list2 = db("action_item")->where("type",1)->order("sort asc")->select();
		//$ticket_config = db('system')->field('value')->where('name', 'gold_config')->find();
	    $ticket_config = get_config('gold_config');
	    $res=db("prizelogs")->count("id");
		if(!$res){
			$res=0;
		}
		$this->assign('res',$res);
	    $this->assign('config',$ticket_config);
		$this->assign('list',$list);
		$this->assign('list2',$list2);
		return $this->fetch();
	}
	
	//兑奖记录列表
	public function cash_list() {
		$list=db("prizelogs")->alias('a')->join("action_item b","a.prize_id=b.id",'LEFT')
		->where("user_id",session("user_info")['id'])
		->where("b.type",2)
		->where("a.status",2)
		->field("a.*,b.name")->select();
		$this->assign('list',$list);
		return $this->fetch();
	}
	
	//兑奖信息核销
	public function hexiao() {
    	if($_POST){
    		$id = input('id');
			$pwd = input('pwd');

			//ticket_config$ticket_config = db('system')->field('value')->where('name', 'ticket_config')->find();
		   	$ticket_config = get_config('ticket_config');
			//核销密码
			$jp_password = $ticket_config['jp_password'];
			
			if($pwd!=$jp_password){
				return json(['code'=>402,'msg'=>'密码错误']);
			}
			
       	 	$parm['status'] = 2;  
       	 	$result = db('prizelogs')->where('id',input('id'))->update($parm);
	        if($result){
				return json(['code'=>200,'msg'=>'操作成功']);
	        }else{
	       		return json(['code'=>402,'msg'=>'操作失败']);
	        }
        }
	}

	
	//兑奖协议
	public function xy_list() {
		//$ticket_config = db('system')->field('value')->where('name', 'xieyi')->find();
	   	$ticket_config = get_config('xieyi');
		$this->assign('xieyi',$ticket_config);
		return $this->fetch();
	}
	
	
	//商家详情
	public function shop_page() {
		$user_id = session('user_info')['id'];	
		$agent_id = input("agent_id");
		$agent_info = db('agent')->find($agent_id);
		db("agent")->where("id",$agent_id)->setInc("count");
		$this->assign('agent_info', $agent_info);
		$activity_info = preg_split('/[;\r\n]+/s', $agent_info['activity']);
		$this->assign('activity_info', $activity_info); 
		
		$url=config('API_DOMAIN')."index/index/shop_page.html?agent_id=$agent_id";
		$this->assign('url',$url);
		
		$share_config = get_config('share_config');
		$this->assign('share_title',$share_config['share_agents']);
		$this->assign('share_content',$share_config['share_agents_content']);
		return $this->fetch();
	}
	
	//验票中心
	public function yanpiao() {
		$user_id = session("user_info")['id'];
		$ticket_info = db('ticketlogs')->where('id',input('id'))->where('user_id',$user_id)->find();
		if(!$ticket_info){
			header("Content-type: text/html; charset=utf-8");
			echo '此票不存在,验票失败!';exit;
		}
		$this->assign('ticket_info', $ticket_info); 
		$user_id=session('user_info')['id'];
		$xfs = db('xiaofei')->where('ticket_id',input('id'))->where('user_id',$user_id)->select();
		$list = db('ticket_items')->order('sort desc')->select();
		foreach($list as $k=>$v){
			$list[$k]['belive']=$v['nums'];//剩余
			if($ticket_info['type']==2){//免费票入场券固定为3次
				$list[$k]['belive']=3;//剩余
			}
			foreach($xfs as $k1=>$v1){
				if($v1['item_id']==$v['id']){
					if($ticket_info['type']==2){//免费票入场券固定为3次
						$list[$k]['belive']=3-$v1['nums'];
					}else{
						$list[$k]['belive']=$v['nums']-$v1['nums'];
					}
				}
			}
		}
		
		$ticket = $ticket_info['id'];
		$sn = $ticket_info['sn'];
		$url=config('API_DOMAIN')."index/index/receiveticket.html?m=$ticket&sn=$sn";
		$this->assign("url",$url);		
		$this->assign('list', $list); 
		return $this->fetch();
	}
	
	//自定义分享设置
	function share_config(){
		return share_config();
	}
	
	//赠送票领取页面
	function receiveticket(){
		$ticket_info = db('ticketlogs')->where('id',input('m'))->where('sn',input('sn'))->find();
		if(!$ticket_info){
			return $this->fetch("lingqu_sb1");
		}
		$this->assign('ticket_info', $ticket_info); 
		$xfs = db('xiaofei')->where('ticket_id',input('m'))->select();
		$list = db('ticket_items')->order('sort desc')->select();
		foreach($list as $k=>$v){
			$list[$k]['belive']=$v['nums'];//剩余
			if($ticket_info['type']==2){//免费票入场券固定为3次
				$list[$k]['belive']=3;//剩余
			}
			foreach($xfs as $k1=>$v1){
				if($v1['item_id']==$v['id']){
					if($ticket_info['type']==2){//免费票入场券固定为3次
						$list[$k]['belive']=3-$v1['nums'];
					}else{
						$list[$k]['belive']=$v['nums']-$v1['nums'];
					}
				}
			}
		}
		
		$this->assign('status', $ticket_info['use_status']);
		$this->assign('user_id', $ticket_info['user_id']);
		$this->assign('list', $list);
		return $this->fetch();
	}
	
	//领取票逻辑
	function share_ticket(){
		$user_info = db("member")->where("open_id",session("openid"))->find();
		$user_id = $user_info['id'];
		//票sn
		$sn = input('sn');
		$ticket_info = db('ticketlogs')->where('sn',$sn)->where('user_id',input("user_id"))->find();
		if($ticket_info){
			//免费票
			if($ticket_info['type']==2){
				return json(["code"=>400,'msg'=>'该票是免费票，无法领取']);			
			}
			//已使用
			if($ticket_info['use_status']==2){
				return json(["code"=>400,'msg'=>'该票已被使用，无法领取']);			
			}
			
			$data['user_id'] =input('user_id');
			$data['add_time'] = now_time();
			$data['reuser_id'] = $user_info['id'];
			$data['ticket_id'] = $ticket_info['id'];
			$res = db("receivelogs")->insert($data);
			
			if($res){
				//修改票的持有者，状态改为2 已使用
				$datas['user_id'] = $user_info['id'];
				$datas['use_status'] = 2;
				$result = db('ticketlogs')->where('sn',$sn)->update($datas);
				if ($result !== false) {
					return json(["code"=>200,'msg'=>'领取成功']);
				} else {
					return json(["code"=>400,'msg'=>'领取失败']);
				}				
			}else{
				return json(["code"=>400,'msg'=>'领取失败']);
			}	
		}
		return $this->fetch();
	}
	

	//购票
	public function buy_mticket(){
		$user_id=session('user_info')['id'];
		//$ticket_config = db('system')->field('value')->where('name', 'ticket_config')->find();
	   	$ticket_config = get_config('ticket_config');
		$where['user_id'] = $user_id;
		$where['type'] = 1;
		//购票价格
		$price=$ticket_config['ticket_price'];

		$data['user_id'] = $user_id;
		$data['add_time'] = now_time();
		$data['balance'] = config("balance");
		$data['pay_balance'] = $price;
		$data['type'] = 1;
		$result = db("ticketlogs")->insert($data);
		if($result){
			return json(["code"=>200,'msg'=>'购买成功']);
		}else{
			return json(["code"=>400,'msg'=>'购买失败']);
		}
	}
	
	//免费票领取
	public function freeticket(){
		$user_id = session("user_info")['id'];
		if(!$user_id){
			echo '用户未注册领取失败';exit;
		}
		
		$agent_id = input('agent_id');
		$agent_info = db('agent')->where('id',$agent_id)->find();
		if($agent_info){
			//免费票为0
			if($agent_info['givenum']==0){
				$this->assign('msg','该商家没有乐享套票，无法领取');
				return $this->fetch("free_sb");		
			}
			
			//在同一个商家只能领取一次免费票
			$where['agent_id'] = $agent_id;
			$where['user_id'] = $user_id;
			$where['is_sjzs'] = 1;
			$free_count = db('ticketlogs')->where($where)->count();
			if($free_count>0){
				$this->assign('msg','已在该商家领取过乐享套票，无法重复领取');
				return $this->fetch("free_sb");
			}		
		
			$data['user_id'] = $user_id;
			$data['add_time'] = now_time();
			$data['type'] = 1;  //赠送票也设为套票
			$data['is_sjzs'] = 1;  //是否为商家赠送票  1 是  0 否
			$data['status'] = 2; 
			$data['agent_id'] = $agent_id;
			$sn = order_create_no();
			$data['sn'] = $sn; 
			$result = db("ticketlogs")->insert($data);
			if($result){				
				db("agent")->where('id',$agent_id)->setDec("givenum",1);
			}else{
				$this->assign('msg','领取失败');
				return $this->fetch("free_sb");
			}
		}
		$this->assign('msg','领取成功');
		return $this->fetch("free_cg");
	}

	//夺宝攻略
	public function duobao_page(){
		$user_id = session('user_info')['id'];	
		//$ticket_config = db('system')->field('value')->where('name', 'gl_config')->find();
	   	$ticket_config = get_config('gl_config');
		$this->assign('gl_config',$ticket_config);

		$win_info = db('prizelogs')->alias('a')
			->join('action_prize b','a.prize_id = b.id','LEFT')
			->join('member c','a.user_id = c.id','LEFT')
			->field('a.*,b.name,c.logo')
			->order('a.add_time desc')->limit(8)->select();
		$this->assign('list',$win_info);
		
		$ticket_info = db('ticketlogs')->alias('a')
			->join('member b','a.user_id = b.id','LEFT')
			->field('a.*,b.mobile,b.logo')
			->order('a.add_time desc')->limit(8)->select();
		$this->assign('list1',$ticket_info);
		
		$url=config('API_DOMAIN')."index/index/duobao_page.html";
		$this->assign('url',$url);
		
		$share_config = get_config('share_config');
		$this->assign('share_title',$share_config['share_dbgl']);
		$this->assign('share_content',$share_config['share_dbgl_content']);
		return $this->fetch();
	}
	
	function map(){
		$this->assign("lng",input("lng"));
		$this->assign("lat",input("lat"));
		$this->assign("name",input("name"));
		return $this->fetch();
	}	
}
